//
//  LXTimeScrollerVC.m
//  bgms_d
//
//  Created by lachesis-zhu on 2019/3/6.
//  Copyright © 2019 lachesis-zhu. All rights reserved.
//

#import "LXTimeScrollerVC.h"
#import "LXAlertModel.h"
#import "LXDevSettingModel.h"
#import "LXLocalNotification.h"
#import <UserNotifications/UserNotifications.h>

@interface LXTimeScrollerVC () <UIPickerViewDelegate, UIPickerViewDataSource, UITextViewDelegate>

@property (nonatomic, strong) NSMutableArray *minuteArray;
@property (nonatomic, strong) NSMutableArray *secondArray;
@property (nonatomic, strong) NSMutableArray *alertArray;
@property (nonatomic, strong) LXLocalNotification *localNoti;

@end

@implementation LXTimeScrollerVC

#pragma mark -  public method

#pragma mark -  life cycle
- (void)dealloc
{
    [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillShowNotification object:nil];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillHideNotification object:nil];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self initializationData];
    [self addNotification];
    
    [self loadUI];
    
    [self loadViewDatas];
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
}

- (void)viewDidAppear:(BOOL)animated
{
  
}

#pragma mark -  over write

#pragma mark -  setter & getter

#pragma mark -  private method
- (void)initializationData
{
    self.localNoti = [[LXLocalNotification alloc] init];
    self.alertArray = [[NSMutableArray alloc] initWithArray:[self getObjectForKey:@"alertData"]];
    NSDictionary *getDic = [self.alertArray objectAtIndex:self.foodItem.placeNum];
    if ([getDic[@"alert"] isEqualToString:@"YES"]) {
        self.remarkTextView.text = getDic[@"titleString"];
        [self.minutePick selectRow:[getDic[@"minite"] integerValue] inComponent:0 animated:YES];
        [self.secondPick selectRow:[getDic[@"second"] integerValue] inComponent:0 animated:YES];
    }
}

- (void)loadUI
{
    self.view.backgroundColor = kAppBackgroundColor;
    [self buildNavi];
    
    self.remarkTextView.layer.cornerRadius = 2;
    self.remarkTextView.layer.borderColor = kAppDeepLineColor.CGColor;
    self.remarkTextView.layer.borderWidth = 0.5;
    self.remarkTextView.layer.masksToBounds = YES;
    self.remarkTextView.returnKeyType = UIReturnKeyDone;
    self.remarkTextView.delegate = self;
}

- (void)loadViewDatas
{
    
}

- (void)buildNavi
{

}

- (void)keyboardWillShow:(NSNotification *)notification {
    //获取键盘高度，在不同设备上，以及中英文下是不同的
    CGFloat kbHeight = [[notification.userInfo objectForKey:UIKeyboardFrameEndUserInfoKey] CGRectValue].size.height;
    
    //计算出键盘顶端到inputTextView panel底端的距离(加上自定义的缓冲距离INTERVAL_KEYBOARD)
    CGFloat offset = kbHeight;

    // 取得键盘的动画时间，这样可以在视图上移的时候更连贯
    double duration = [[notification.userInfo objectForKey:UIKeyboardAnimationDurationUserInfoKey] doubleValue];
    
    //将视图上移计算好的偏移
    if(offset > 0) {
        [UIView animateWithDuration:duration animations:^{
            self.topToView.constant = -offset + 66;
            self.bottomToView.constant = offset;
        }];
    }
}

///键盘消失事件
- (void)keyboardWillHide:(NSNotification *)notify {
    // 键盘动画时间
    double duration = [[notify.userInfo objectForKey:UIKeyboardAnimationDurationUserInfoKey] doubleValue];
    //视图下沉恢复原状
    [UIView animateWithDuration:duration animations:^{
        self.topToView.constant = 10;
        self.bottomToView.constant = 0;
    }];
}

#pragma mark -  notification
- (void)addNotification
{
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(keyboardWillHide:) name:UIKeyboardWillHideNotification object:nil];
}

#pragma mark -  network


#pragma mark -  event handle
- (IBAction)removeDown:(id)sender {
    if (self.alertArray.count > self.foodItem.placeNum) {
        NSMutableDictionary *dic = [[NSMutableDictionary alloc] init];
        [dic setObject:@"NO" forKey:@"alert"];
        [self.alertArray replaceObjectAtIndex:self.foodItem.placeNum withObject:dic];
    }
    [self saveObject:self.alertArray forKey:@"alertData"];
    [self.navigationController popViewControllerAnimated:YES];
}

- (IBAction)presetDown:(id)sender {
    if (self.alertArray.count > self.foodItem.placeNum) {
        NSMutableDictionary *dic = [[NSMutableDictionary alloc] init];
        [dic setObject:@"YES" forKey:@"alert"];
        [dic setObject:@"YES" forKey:@"setting"];
        NSInteger minute = [self.minutePick selectedRowInComponent:0];
        [dic setObject:[self.minuteArray objectAtIndex:minute] forKey:@"minite"];
        NSInteger second = [self.secondPick selectedRowInComponent:0];
        [dic setObject:[self.secondArray objectAtIndex:second] forKey:@"second"];
        [dic setObject:self.remarkTextView.text forKey:@"titleString"];
        NSDate *newDate = [NSDate dateWithTimeIntervalSinceNow:(minute * 60 + second)];
        NSDateFormatter *formate = [[NSDateFormatter alloc] init];
        [formate setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
        [dic setObject:[formate stringFromDate:newDate] forKey:@"alertTime"];
        [dic setObject:[NSString stringWithFormat:@"%ld", (long)self.foodItem.placeNum] forKey:@"placeNum"];
        [dic setObject:[NSString stringWithFormat:@"%@#%ld %@", NSLocalizedString(@"Probe", nil), self.foodItem.placeNum + 1, NSLocalizedString(@"TheTimerSetted", nil)] forKey:@"name"];
        [dic setObject:[NSString stringWithFormat:@"%@#%ld %@", NSLocalizedString(@"Probe", nil), self.foodItem.placeNum + 1, NSLocalizedString(@"TheTimerSetted", nil)] forKey:@"alertedName"];
        [self.alertArray replaceObjectAtIndex:self.foodItem.placeNum withObject:dic];
        NSDictionary *devDic = [self getObjectForKey:@"DevSetting"];
        BOOL notifBool = [devDic[@"connectNotif"] boolValue];
        if (notifBool) {
            [self.localNoti addLocalNoticeTitle:dic[@"name"] alertBody:dic[@"titleString"] time:newDate withPlace:[NSString stringWithFormat:@"%ld", (long)self.foodItem.placeNum] type:@"1"];
        }
    }
    [self saveObject:self.alertArray forKey:@"alertData"];
    [self.navigationController popViewControllerAnimated:YES];
}

#pragma mark -  delegate
#pragma mark UITextFieldDelegate
- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text{
    if ([text isEqualToString:@"\n"]){
        [textView resignFirstResponder];
        return NO;
    }
    return YES;
}

- (BOOL)textViewShouldEndEditing:(UITextView *)textView
{
    [textView resignFirstResponder];
    return YES;
}

#pragma mark UIPickerViewDelegate
- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView
{
    return 1;
}

- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component
{
    if (pickerView == self.minutePick) {
        return self.minuteArray.count;
    }
    return self.secondArray.count;
}

- (CGFloat)pickerView:(UIPickerView *)pickerView rowHeightForComponent:(NSInteger)component
{
    return 30;
}

- (NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component
{
    if (self.minutePick == pickerView) {
        return [self.minuteArray objectAtIndex:row];
    }
    return [self.secondArray objectAtIndex:row];
}

- (void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component
{
    
}
#pragma mark -  lazy load
- (NSMutableArray *)minuteArray {
    if (!_minuteArray) {
        _minuteArray = [[NSMutableArray alloc] init];
        for (NSInteger i = 0; i < 240; i ++) {
            [_minuteArray addObject:[NSString stringWithFormat:@"%ld", i]];
        }
    }
    return _minuteArray;
}

- (NSMutableArray *)secondArray {
    if (!_secondArray) {
        _secondArray = [[NSMutableArray alloc] init];
        for (NSInteger i = 0; i < 60; i ++) {
            [_secondArray addObject:[NSString stringWithFormat:@"%ld", i]];
        }
    }
    return _secondArray;
}
#pragma mark -  memoryWarning

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
